package com.mrd.gtimp.business.service;

import com.mrd.base.BaseBiz;
import com.mrd.constant.BaseTypeConstant;
import com.mrd.exception.QueryException;
import com.mrd.gtimp.business.entity.DeclarationOffer;
import com.mrd.gtimp.business.repository.DeclarationOfferDao;
import com.mrd.spring.repository.BaseRepository;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

/**
 * <p>
 * application name: gtimp
 * <p>
 * copyright: Copyright@2012 明睿达科技有限公司
 */

/**
 * @author yangyl
 */
@Service
public class DeclarationOfferBiz extends BaseBiz<DeclarationOffer> {
	@Resource
	private DeclarationOfferDao declarationOfferDao;

	/**
	 * 根据供应商id获取当前生效的的报价
	 * @param supCompanyId
	 *            供应商id
	 * @return 生效的报价
	 */
	public DeclarationOffer findValidOffer(String supCompanyId) {
		List<DeclarationOffer> offers = declarationOfferDao
		        .findValidOffer(supCompanyId, DateUtils.truncate(new Date(), Calendar.DATE));
		if(CollectionUtils.isEmpty(offers)) {
			return null;
		} else {
			return offers.get(0);
		}
	}

	// 根据关键字查询关区号码和对应的名称 sql
	private String find(String keyWord) {
		String hql = "select distinct offer.port, offer.port_code from T_BIZ_DECLARATION_OFFER offer where offer.state='OS05' "
		        + "and offer.price_begin_time <=  to_date('"
		        + new SimpleDateFormat("yyyy-MM-dd").format(new Date())
		        + "','yyyy-MM-dd') and offer.price_end_time >= to_date('"
		        + new SimpleDateFormat("yyyy-MM-dd").format(new Date()) + "','yyyy-MM-dd')";
		if(StringUtils.isNotEmpty(keyWord)) {
			hql += " and (offer.port like '%" + keyWord.trim() + "%' or offer.port_code like '%"
			        + keyWord.trim() + "%')";
		}
		return hql;
	}

	/**
	 * 根据关键字查询关区号码和对应的名称
	 * @param keyWord
	 *            关区号码或者关区名称
	 * @return 只有关区代码和关区名称，其他为空
	 */
	public List<DeclarationOffer> findOfferPortWithCode(String keyWord,Pageable pageable)
	        throws QueryException {
		List<Object> objects = findObjectBySql(find(keyWord), pageable.getPageNumber(), pageable
		        .getPageSize(), null);
		return result(objects);
	}

	/**
	 * 申报口岸下拉 (2.0一线通)
	 */
	public List<DeclarationOffer> findOfferPortOfCode(String keyWord) throws QueryException {
		List<Object> objects = findObjectBySql(find(keyWord), 0, 100, null);
		return result(objects);
	}

	// 申报口岸 返回结果
	private List<DeclarationOffer> result(List<Object> objects) {
		List<DeclarationOffer> declarationOffers = new ArrayList<>();
		for(Object object : objects) {
			DeclarationOffer declarationOffer = new DeclarationOffer();
			Object[] obj = (Object[]) object;
			declarationOffer.setPort(obj[0].toString());
			declarationOffer.setPort_code(obj[1].toString());
			declarationOffers.add(declarationOffer);
		}
		return declarationOffers;
	}

	/**
	 * 在将报价发送包页面之前需要做的事情
	 * 1、收集状态为OS05的报价
	 * 2、每个报关行报价为OS05状态的数量大于1时需要检查是否有报价可以关闭。
	 * @param offerList
	 */
	public void beforePrintToPage(List<DeclarationOffer> offerList) {
		Map<String, List<DeclarationOffer>> effectiveOfferMap = new HashMap<>();
		for(DeclarationOffer offer : offerList) {
			if(BaseTypeConstant.DECLARATIONOFFERSTATE_05.equals(offer.getState())) {
				List<DeclarationOffer> list = effectiveOfferMap
				        .get(offer.getDeclaration_company_id());
				if(list == null) {
					list = new ArrayList<>();
					effectiveOfferMap.put(offer.getDeclaration_company_id(), list);
				}
				list.add(offer);
			}
		}
		final List<DeclarationOffer> needCloseOffers = new ArrayList<>(); // 需要将状态改为结束的报价
		for(List<DeclarationOffer> declarationOffers : effectiveOfferMap.values()) {
			/**
			 * 按结束时间进行排序，方便后面逻辑运算
			 */
			declarationOffers.sort(new Comparator<DeclarationOffer>() {
				@Override
				public int compare(DeclarationOffer o1,DeclarationOffer o2) {
					if(o1.getPrice_end_time().getTime() - (o2.getPrice_end_time().getTime()) == 0) {
						return o1.getPrice_begin_time().compareTo(o2.getPrice_begin_time());
					}
					return o1.getPrice_end_time().compareTo(o2.getPrice_end_time());
				}
			});
			if(declarationOffers.size() > 1) {
				 //DeclarationOffer effectiveOfferNow = null;
				long now = System.currentTimeMillis();
				/**
				 * 找到正在生效的报价
				 * 找到生效报价后的其他后续报价设置为结束
				 */
				for(DeclarationOffer declarationOffer : declarationOffers) {
					if(declarationOffer.getPrice_begin_time().getTime() < now
					        && declarationOffer.getPrice_end_time().getTime() < now) {
						DeclarationOffer effectiveOfferNow = declarationOffer;
						if(effectiveOfferNow != null) {
							declarationOffer.setState(BaseTypeConstant.DECLARATIONOFFERSTATE_04);
							needCloseOffers.add(declarationOffer);
						}
					}

				}
			}
		}
		final BaseRepository declarationOfferRepository = this.baseRepository;
		// 更新报价状态
		new Thread() {
			@Override
			public void run() {
				declarationOfferRepository.save(needCloseOffers);
			}
		}.run();
	}



	@Resource
	// 该处指定注入BaseRepository的dao对象
	@Qualifier("declarationOfferDao")
	public void setBaseRepository(BaseRepository<DeclarationOffer, String> baseRepository) {
		super.baseRepository = baseRepository;
	}

}
